import type { Reactive } from "vue";

interface Filter {
  field: string;
  operator: string;
  value: any;
}

function transformTime(time: number, isSeconds = false): number {
  const dateObj = new Date(time);
  const timestamp = dateObj.getTime();
  return isSeconds ? timestamp : Math.floor(timestamp / 1000);
}

export function getFilter(form: Reactive<any>): Filter[] {
  let filters = [];
  for (const key in form) {
    if (form[key] !== "" && form[key] !== null && form[key] !== undefined) {
      let filter: Filter;
      let type = typeof form[key];
      // 如果是0 当做nubmer处理
      if (form[key] === 0) {
        type = "number";
      }
      // 尝试吧type转换为int类型，再判断
      if (type == "string") {
        type = isNaN(Number(form[key])) ? type : "number";
      }
      // 判断是字符串 或者 int  或者 数组
      switch (type) {
        case "string":
          filter = {
            field: key,
            operator: "like",
            value: "%" + form[key] + "%"
          };
          break;
        case "number":
          filter = {
            field: key,
            operator: "=",
            value: isNaN(Number(form[key])) ? form[key] : Number(form[key])
          };
          break;
        case "object":
          // 判断师傅是length=2的数组，并且是时间格式
          if (form[key].length == 2) {
            const startTime = transformTime(form[key][0]);
            const endTime = transformTime(form[key][1]);
            filter = {
              field: key,
              operator: "between",
              value: [startTime, endTime]
            };
          }
          break;
      }
      if (filter) {
        filters.push(filter);
      }
    }
  }
  return filters;
}
